package hey.dylan.model;

import hey.dylan.handler.ModelException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GeneralModel implements Serializable {

    /* 当前节点属性 */
    private String name;

    /* 当前节点值 */
    private String value;

    /* 当前节点子节点集合 */
    private Map<String, List<GeneralModel>> childrenMap;

    /* 有参构造 */
    public GeneralModel(String name) {
        this.name = name;
        this.value = "";
    }

    /* 添加子节点 */
    public void add(String name, String value) {
        GeneralModel model = new GeneralModel(name);
        model.setValue(value);
        this.add(model);
    }

    /* 添加子节点（重载） */
    public void add(GeneralModel model) {

        if (this.childrenMap == null) {
            this.childrenMap = new HashMap<>();
        }
        if (this.childrenMap.containsKey(model.getName())) {
            this.childrenMap.get(model.getName()).add(model);
        } else {
            List<GeneralModel> list = new ArrayList<>();
            list.add(model);
            this.childrenMap.put(model.getName(), list);
        }

    }

    /* 获取子节点 */
    public GeneralModel get(String name) {
        return this.get(name, 0);
    }

    public GeneralModel get(String name, int index) {

        if (this.childrenMap == null) {
            throw new ModelException("节点<" + this.name + ">中不存在任何子节点");
        }
        if (!this.childrenMap.containsKey(name)) {
            throw new ModelException("节点<" + this.name + ">中不存在子节点<" + name + ">");
        }
        if (this.childrenMap.size() < index + 1) {
            throw new ModelException("节点<" + this.name + ">中的子节点<" + name + ">的个数只有" + this.childrenMap.size() + "个，你的索引(" + index + ")已超出边界");
        }
        return this.childrenMap.get(name).get(index);

    }

    /* 判断是否存在该子节点 */
    public boolean isContain(String name) {
        return this.childrenMap == null ? false : this.childrenMap.containsKey(name);
    }

    /* 获取子节点集合 */
    public List<GeneralModel> getChildrenList(String name) {
        return this.childrenMap.get(name);
    }

    public String getChildValue(String name){
        return this.childrenMap.get(name).get(0).getValue();
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}
